package it.blueocean.acanto.util;

import java.util.Properties;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Named;

import net.sf.ehcache.CacheManager;

import org.hibernate.cache.Cache;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.CacheProvider;
import org.hibernate.cache.Timestamper;

@Named("ehCacheProvider")
public class EhCacheProvider implements CacheProvider
{
	private static Logger logger = Logger.getLogger(EhCacheProvider.class.getName());

	@Inject
	@Named("cacheManager")
	private CacheManager cacheManager;

	public Cache buildCache(String name, Properties properties) throws CacheException
	{
		try
		{
			net.sf.ehcache.Cache cache = cacheManager.getCache(name);
			if(cache == null)
			{
				logger.warning("Could not find configuration [" + name + "]; using defaults.");
				cacheManager.addCache(name);
				cache = cacheManager.getCache(name);
				logger.config("started EHCache region: " + name);
			}
			else
			{
				logger.config("found EHCache region: " + name);
			}
			return new EhCache(cache);
		}
		catch (net.sf.ehcache.CacheException e)
		{
			throw new CacheException(e);
		}
	}

	public long nextTimestamp()
	{
		return Timestamper.next();
	}

	public void start(Properties properties) throws CacheException
	{
		cacheManager = CacheManager.getInstance();
	}

	public void stop()
	{
		// Spring will do this already
	}

	public boolean isMinimalPutsEnabledByDefault()
	{
		return false;
	}

	public CacheManager getCacheManager()
	{
		return cacheManager;
	}

	public void setCacheManager(CacheManager manager)
	{
		cacheManager = manager;
	}

	private class EhCache extends org.hibernate.cache.EhCache
	{
		public EhCache(net.sf.ehcache.Cache cache)
		{
			super(cache);
		}

		public void destroy() throws CacheException
		{
			// Spring will do this already
		}

	}
}
